using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;

namespace WinForm_Mes.CheckManagement

{
    public partial class UserShowForm : DevExpress.XtraEditors.XtraForm
    {
        #region 私有字段
        private readonly int _pageSize = 10;
        private int _pageIndex = 1;
        private int _total = 0;
        private readonly string _baseUrl = "http://localhost:5078/api/User/";
        private readonly HttpClient _httpClient;
        #endregion

        #region 构造函数
        public UserShowForm()
        {
            _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
            InitializeComponent();
            InitializeControls();
            BindEvents();
            LoadInitialData();
        }
        #endregion

        #region 初始化和事件绑定
        private void InitializeControls()
        {
            Text = "客户管理";
            SetupGridColumns();
            SetupGridViewOptions();
            ApplyGridStyles();
        }

        private void SetupGridViewOptions()
        {
            // 设置网格视图的显示选项
            gridView1.OptionsView.ShowAutoFilterRow = true; // 显示过滤行
            gridView1.OptionsView.ColumnAutoWidth = false; // 禁用自动列宽
            gridView1.OptionsView.ShowGroupPanel = false; // 隐藏分组面板
            gridView1.OptionsCustomization.AllowColumnMoving = true; // 允许列移动
            gridView1.OptionsCustomization.AllowColumnResizing = true; // 允许列宽调整
            gridView1.OptionsView.RowAutoHeight = true; // 自动行高
            gridView1.OptionsView.ShowIndicator = true; // 显示行号
            
            // 优化选中行的显示
            gridView1.FocusRectStyle = DrawFocusRectStyle.RowFocus;
            gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
            gridView1.OptionsSelection.EnableAppearanceFocusedRow = true;

            // 设置行高
            gridView1.RowHeight = 30;
            
            // 优化表格布局
            gridControl1.Dock = DockStyle.Fill;
            gridView1.OptionsView.ColumnHeaderAutoHeight = DefaultBoolean.True;
        }

        private void ApplyGridStyles()
        {
            // 美化表格外观
            // 设置表头样式
            gridView1.Appearance.HeaderPanel.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
            gridView1.Appearance.HeaderPanel.BackColor = Color.FromArgb(78, 116, 171);
            gridView1.Appearance.HeaderPanel.ForeColor = Color.White;
            gridView1.Appearance.HeaderPanel.TextOptions.HAlignment = HorzAlignment.Center;

            // 设置行样式
            gridView1.Appearance.Row.Font = new Font("微软雅黑", 9F);
            gridView1.Appearance.Row.TextOptions.HAlignment = HorzAlignment.Center;

            // 设置奇偶行颜色
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.OptionsView.EnableAppearanceOddRow = true;
            gridView1.Appearance.EvenRow.BackColor = Color.FromArgb(240, 244, 250);
            gridView1.Appearance.OddRow.BackColor = Color.White;

            // 设置选中行样式
            gridView1.Appearance.FocusedRow.BackColor = Color.FromArgb(183, 211, 255);
            gridView1.Appearance.FocusedRow.ForeColor = Color.Black;

            // 美化按钮样式
            ApplyButtonStyles();
        }

        private void ApplyButtonStyles()
        {
            // 统一按钮样式
            foreach (Control control in panelControl1.Controls)
            {
                if (control is SimpleButton button)
                {
                    button.Appearance.BackColor = Color.FromArgb(78, 116, 171);
                    button.Appearance.ForeColor = Color.White;
                    button.Appearance.Font = new Font("微软雅黑", 9F);
                    button.Appearance.Options.UseBackColor = true;
                    button.Appearance.Options.UseForeColor = true;
                    button.Appearance.Options.UseFont = true;
                }
            }

            // 调整面板样式
            panelControl1.Appearance.BackColor = Color.FromArgb(240, 244, 250);
            panelControl2.Appearance.BackColor = Color.White;
        }

        private void BindEvents()
        {
            this.gridControl1.Load += GridControl1_Load;
            this.btnSearch.Click += async (s, e) => await RefreshData();
            this.btnAdd.Click += AddUser;
            this.btnDelete.Click += DeleteUser;
            this.btnExport.Click += ExportData;
            this.gridView1.DoubleClick += GridView1_DoubleClick;
            this.Load += UserShowForm_Load;
            this.Resize += UserShowForm_Resize;
        }

        private void UserShowForm_Load(object sender, EventArgs e)
        {
            AdjustColumnWidths();
        }

        private void UserShowForm_Resize(object sender, EventArgs e)
        {
            AdjustColumnWidths();
        }

        private void AdjustColumnWidths()
        {
            if (gridView1 == null || gridView1.Columns.Count == 0) return;

            // 获取GridControl的可用宽度
            int totalWidth = gridControl1.Width - 30; // 减去滚动条和边框宽度
            
            // 设置各列的相对宽度比例
            var widthRatios = new Dictionary<string, double>
            {
                { "userCode", 0.15 },
                { "userName", 0.20 },
                { "userShortName", 0.15 },
                { "phone", 0.15 },
                { "userType", 0.15 },
                { "email", 0.20 }
            };

            // 应用宽度比例
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView1.Columns)
            {
                if (widthRatios.ContainsKey(column.FieldName))
                {
                    column.Width = (int)(totalWidth * widthRatios[column.FieldName]);
                }
            }
        }

        private void LoadInitialData()
        {
            _ = LoadGridDataAsync();
        }
        #endregion

        #region Grid设置
        private void SetupGridColumns()
        {
            // 确保GridView已初始化
            if (gridView1 == null || gridView1.Columns == null || gridView1.Columns.Count == 0) return;

            // 设置所有列为只读
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in this.gridView1.Columns)
            {
                col.OptionsColumn.AllowEdit = false;
                col.OptionsColumn.ReadOnly = true;
                col.MinWidth = 100; // 设置最小列宽
            }

            // 检查列对象是否存在，然后设置字段名
            if (userCode != null) userCode.FieldName = "userCode";
            if (userName != null) userName.FieldName = "userName";
            if (userShortName != null) userShortName.FieldName = "userShortName";
            if (phone != null) phone.FieldName = "phone";
            if (userType != null) userType.FieldName = "userType";
            if (email != null) email.FieldName = "email";

            // 设置列宽（会被自动调整覆盖）
            if (userCode != null) userCode.Width = 100;
            if (userName != null) userName.Width = 120;
            if (userShortName != null) userShortName.Width = 100;
            if (phone != null) phone.Width = 120;
            if (userType != null) userType.Width = 100;
            if (email != null) email.Width = 150;
        }
        #endregion

        #region 事件处理
        private void GridControl1_Load(object sender, EventArgs e)
        {
            _ = LoadGridDataAsync();
        }

        private void GridView1_DoubleClick(object sender, EventArgs e)
        {
            var focusedRow = gridView1.GetFocusedRow() as UserDto;
            if (focusedRow != null)
            {
                // 打开客户编辑窗体
                var userDto = new AddUserForm.UserDto
                {
                    userCode = focusedRow.userCode,
                    userName = focusedRow.userName,
                    password = "", // 密码不从列表中获取
                    userShortName = focusedRow.userShortName,
                    phone = focusedRow.phone,
                    userType = focusedRow.userType,
                    email = focusedRow.email
                };
                
                AddUserForm editUserForm = new AddUserForm(AddUserForm.FormMode.Edit, userDto);
                if (editUserForm.ShowDialog() == DialogResult.OK)
                {
                    // 刷新数据
                    _ = RefreshData();
                }
            }
        }

        private void AddUser(object sender, EventArgs e)
        {
            try
            {
                // 打开添加客户窗体
                AddUserForm addUserForm = new AddUserForm(AddUserForm.FormMode.Add);
                if (addUserForm.ShowDialog() == DialogResult.OK)
                {
                    // 刷新数据
                    _ = RefreshData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加客户时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void DeleteUser(object sender, EventArgs e)
        {
            try
            {
                var focusedRow = gridView1.GetFocusedRow() as UserDto;
                if (focusedRow == null)
                {
                    MessageBox.Show("请选择要删除的客户", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (MessageBox.Show($"确定要删除客户 {focusedRow.userName} 吗？", "确认", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }

                var url = $"{_baseUrl}DeleteUser?userCode={focusedRow.userCode}";
                var response = await _httpClient.DeleteAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    await RefreshData();
                }
                else
                {
                    MessageBox.Show("删除失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除客户时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ExportData(object sender, EventArgs e)
        {
            try
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Filter = "Excel文件|*.xlsx",
                    Title = "导出Excel",
                    FileName = $"客户列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                };

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    gridControl1.ExportToXlsx(saveFileDialog.FileName);
                    MessageBox.Show("导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 数据加载
        private async Task RefreshData()
        {
            _pageIndex = 1;
            await LoadGridDataAsync();
        }

        private async Task LoadGridDataAsync()
        {
            try 
            {
                gridControl1.UseWaitCursor = true;
                
                var userCode = txtUserCode.Text.Trim();
                var userName = txtUserName.Text.Trim();

                // 修改为使用GetUserAll接口
                var url = $"{_baseUrl}GetUserAll?pageIndex={_pageIndex}&pageSize={_pageSize}";
                if (!string.IsNullOrEmpty(userCode))
                {
                    url += $"&userCode={userCode}";
                }
                if (!string.IsNullOrEmpty(userName))
                {
                    url += $"&userName={userName}";
                }

                // 移除调试弹窗，只保留控制台日志
                Console.WriteLine($"请求URL: {url}");

                try
                {
                    var response = await _httpClient.GetFromJsonAsync<PageResult<UserDto>>(url);
                    
                    if (response?.Items != null)
                    {
                        UpdateGridData(response);
                    }
                    else
                    {
                        await LoadAllUsersDirectAsync();
                    }
                }
                catch (Exception)
                {
                    await LoadAllUsersDirectAsync();
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络请求错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                gridControl1.UseWaitCursor = false;
            }
        }

        // 备用方法：直接从后端获取所有用户数据
        private async Task LoadAllUsersDirectAsync()
        {
            try
            {
                var directUrl = $"{_baseUrl}GetUserAll";
                Console.WriteLine($"尝试直接请求: {directUrl}");
                
                var response = await _httpClient.GetAsync(directUrl);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadFromJsonAsync<PageResult<UserDto>>();
                    if (result?.Items != null)
                    {
                        UpdateGridData(result);
                    }
                    else
                    {
                        MessageBox.Show("未能解析返回的数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show($"获取数据失败，状态码: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据加载失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UpdateGridData(PageResult<UserDto> response)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateGridDataInternal(response)));
            }
            else
            {
                UpdateGridDataInternal(response);
            }
        }

        private void UpdateGridDataInternal(PageResult<UserDto> response)
        {
            gridControl1.DataSource = null;
            gridControl1.DataSource = response.Items;
            
            // 调整列宽和显示
            AdjustColumnWidths();
            
            _total = response.Total;
        }
        #endregion

        #region 数据模型
        public class PageResult<T>
        {
            public int Total { get; set; }
            public int PageIndex { get; set; }
            public int PageSize { get; set; }
            public List<T> Items { get; set; }
            public int Code { get; set; }
            public string Message { get; set; }
            public object Data { get; set; }
        }

        public class UserDto
        {
            public string userCode { get; set; } = string.Empty;
            public string userName { get; set; } = string.Empty;
            public string userShortName { get; set; } = string.Empty;
            public string phone { get; set; } = string.Empty;
            public string userType { get; set; } = string.Empty;
            public string email { get; set; } = string.Empty;
        }
        #endregion

        private void UserShowForm_Load_1(object sender, EventArgs e)
        {

        }
    }
} 